<template>
  <div class="flexContent">
    <GoodsSearch title="单位名称" @searchFn="searchFn" @emptyFn="emptyFn" />
    <el-button class="addBtn" v-has="'unit_add'" @click="addFn">新增</el-button>
    <div class="table" id="tableBox"  v-height>
      <div style="flex:1;">
        <vxe-table :column-config="{resizable: true}" border class="tablebox" ref="xTable1" :row-config="{isHover: true}" :scroll-y="{ enabled: true,gt:21 }" align="center" style="width: 100%" size="medium" height="100%">
          <vxe-column type="seq" width="80" title="序号" />
          <vxe-column field="name" title="单位名称" min-width="50"/>
          <!-- <vxe-column field="sort" sortable title="排序" /> -->
          <vxe-column fixed="right" width="150" title="操作" v-if="$showFn(['unit_edit', 'unit_del'])">
            <template v-slot="{ row }">
              <el-button type="text" style="margin-right: 10px" @click="edit(row)"
                v-has="'unit_edit'">修改</el-button>
              <el-button type="text" v-has="'unit_del'" style="margin-right: 10px; color: red"
                @click="$delFn('单位', del, row)">删除</el-button>
            </template>
          </vxe-column>
        </vxe-table>
      </div>
      <div class="paginationBox">
        <el-pagination :current-page="page.pageNum" background :page-sizes="$pageSizes" :page-size="page.pageSize"
          layout="total,->, sizes, prev, pager, next, jumper" :total="page.total" @size-change="handleSizeChange"
          @current-change="handleCurrentChange" />
      </div>
    </div>
    <AddDialog :show-dialog.sync="showDialog" :title="title" @close="close" @btnOk="btnOk">
      <el-form ref="addFormRef" :rules="addRules" :model="addForm" label-width="80px">
        <el-form-item label="单位名称" style="width: 90%" prop="name">
          <el-input v-clearEmoji v-model.trim="addForm.name" @keydown.enter.native="btnOk" placeholder="请输入..."/>
        </el-form-item>
      </el-form>
    </AddDialog>
  </div>
</template>

<script>
import { getUnit, addUnit, updateUnit, delUnit } from "@/api/goods";
import GoodsSearch from "@/components/Goods/GoodsSearchPanel";
import AddDialog from "@/components/Goods/AddDialog";
export default {
  name: "GoodsUnit",
  components: {
    GoodsSearch,
    AddDialog,
  },
  data() {
    return {
      title: "",
      sKeywords: "",
      showDialog: false,
      isSearch: false,
      addForm: {
        name: "",
        sort: "",
      },
      addRules: {
        name: [
          {
            required: true,
            message: "单位名称不能为空",
            trigger: "blur",
          },
          {
            min: 1,
            max: 1,
            message: "单位名称最长为1个字符",
            trigger: "blur",
          },
        ],
        sort: [
          {
            min: 0,
            max: 3,
            message: "排序只能为数字，最多输入三位",
            trigger: "blur",
          },
          {
            // pattern 正则表达式
            pattern: /^\d+$/,
            message: "排序只能为数字，最多输入三位",
            trigger: "blur",
          },
        ],
      },
      page: {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      },
      unitList: [],
      id: "",
    };
  },
  created() {
    this.getUnitList();
  },
  methods: {
    async getUnitList() {
      if (!this.isSearch) {
        this.sKeywords = "";
      }
      const res = await getUnit({ ...this.page, unitName: this.sKeywords });
      if (res.code === 200) {
        const data = res.data;
        this.unitList = data.list;
        this.page.pageSize = data.pageSize;
        this.page.pageNum = data.pageNum;
        this.page.total = data.total;
        console.log(data);
        const $table = this.$refs.xTable1
        $table.loadData(this.unitList);
        console.log("列表", this.unitList);
      } else {
        // this.$message.error(res.message);
      }
    },
    async searchFn(sKeywords) {
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.sKeywords = sKeywords;
      this.isSearch = true;
      this.getUnitList();
    },
    // 控制新增弹窗显示
    addFn() {
      this.title = "新增";
      this.showDialog = true;
    },
    btnOk() {
      // console.log('调用新增接口')
      console.log(this.addForm);
      // 校验
      this.$refs.addFormRef.validate(async (isOK) => {
        if (isOK) {
          // 判断是新增还是修改
          if (this.title === "新增") {
            const res = await addUnit({ ...this.addForm, id: this.id });
            console.log(res);
            if (res.code === 200) {
              this.$message.success("新增成功");
              this.resetPage();
              this.getUnitList();
              // this.$refs.form.resetFields()
            } else {
              // this.$message.error(res.message);
            }
          } else if (this.title === "修改") {
            const res = await updateUnit({ ...this.addForm, id: this.id });
            if (res.code === 200) {
              this.$message.success("修改成功");
              this.resetPage("edit");
              this.getUnitList();
              // this.$refs.form.resetFields()
              console.log("修改res", res);
              console.log("修改", this.addForm);
            } else {
              // this.$message.error(res.message);
            }
          }
          this.addForm.sort = "";
          this.addForm.name = "";
          this.id = "";
          this.showDialog = false;
        } else {
          this.$message.warning("请检查输入信息");
        }
      });
    },
    // 获取条数改变
    handleSizeChange(val) {
      this.page.pageSize = val;
      this.page.pageNum = 1;
      console.log(`每页 ${val} 条`);
      this.getUnitList();
    },
    // 获取页数改变
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.page.pageNum = val;
      this.getUnitList();
    },
    edit(row) {
      this.id = row.id;
      this.addForm.name = row.name;
      this.$set(this.addForm, "sort", String(row?.sort ? row.sort : ""));
      this.title = "修改";
      this.showDialog = true;
    },
    async del(row) {
      console.log(111);
      console.log("删除", row);
      const res = await delUnit({ id: row.id });
      console.log(res);
      if (res.code === 200) {
        // 判断当前数据是不是当页最后一条，如果是页码减1
        this.$message.success("删除成功");
        if (this.unitList.length === 1 && this.page.pageNum > 1)
          this.page.pageNum--;
        this.getUnitList();
      } else {
        // this.$message.error(res.message);
      }
    },
    close() {
      this.$refs.addFormRef.resetFields();
      this.addForm.name = "";
      this.id = "";
      this.addForm.sort = "";
      this.showDialog = false;
    },
    emptyFn() {
      this.isSearch = false;
      this.page = {
        pageNum: 1,
        pageSize: 20,
        total: 0,
      };
      this.sKeywords = "";
      this.getUnitList();
    },
  },
};
</script>

<style scoped lang="scss">
</style>
